package org.apaydin.eksisozluk;

import org.apaydin.BaseFetcher;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

public class TopicFetcherImpl extends BaseFetcher implements Fetcher<EksiTopics>{

    private static final String SEARCH_URL = BASE_URL + "index.asp?a=sr&kw=%s&p=%s";

    private final String keyword;

    public TopicFetcherImpl(String keyword) {
        super();
        this.keyword = keyword;
    }

    @Override
    public void fetch(EksiTopics topics, int page) throws IOException, XPatherException {
        TagNode node = getRootTagNode(getUrl(keyword, page));

        for (TagNode tagNode : evaluateXPath(node, "//ul[@class='index']/li")) {
            TagNode n = evaluateXPath(tagNode, "//a").get(0);
            String href = n.getAttributeByName("href");
            String name = n.getText().toString();
            EksiTopic topic = new EksiTopic(href, name);
            topics.addItem(topic);
        }

        if (topics.getTopics().size() <= 0) {
            return;
        }

        TagNode countNode = evaluateXPath(node, "//div[@class='pagi']").get(0);
        topics.setTopicCount(extractItemcount(countNode.getText()));
        topics.setCurrentPage(parseInt(evaluateXPath(countNode, "//select/option[@selected='selected']").get(0).getText().toString()));
        List<TagNode> as = evaluateXPath(countNode, "//span/a");
        topics.setPageCount(extractPagecount(as));
    }

    protected int extractItemcount(StringBuffer value) {
        return parseInt(value.substring(value.indexOf("(") + 1, value.indexOf(" başlık)")));
    }

    public String getUrl(String keyword, int page){
        return String.format(SEARCH_URL, keyword, String.valueOf(page));
    }


}
